package com.hm.hall.commons.util;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;

/**
 * 关于异常的工具类.
 */
public class ExceptionUtils {

    /**
     * 将CheckedException转换为UncheckedException.
     *
     * @param e xx
     * @return xx
     */
    public static RuntimeException unchecked(Exception e) {
        if (e instanceof RuntimeException) {
            return (RuntimeException) e;
        } else {
            return new RuntimeException(e);
        }
    }

    /**
     * 将ErrorStack转化为String.
     *
     * @param e xx
     * @return xx
     */
    public static String getStackTraceAsString(Exception e) {
        StringWriter stringWriter = new StringWriter();
        e.printStackTrace(new PrintWriter(stringWriter));
        return stringWriter.toString();
    }

    /**
     * 获取组合本异常信息与底层异常信息的异常描述, 适用于本异常为统一包装异常类，底层异常才是根本原因的情况。
     *
     * @param e xx
     * @return xx
     */
    public static String getErrorMessageWithNestedException(Exception e) {
        Throwable nestedException = e.getCause();
        return new StringBuilder().append(e.getMessage()).append(" nested exception is ")
                .append(nestedException.getClass().getName()).append(":").append(nestedException.getMessage())
                .toString();
    }

    /**
     * 获得输出的异常堆栈信息到字符串
     */
    public static String getExceptionPrintStackTrace(Exception ex) {
        String result = "";
        StringWriter sw = null;
        PrintWriter pw = null;
        try {
            sw = new StringWriter();
            pw = new PrintWriter(sw);
            ex.printStackTrace(pw); //将出错的栈信息输出到printWriter中
            result = sw.toString();
            pw.flush();
            sw.flush();
        } finally {
            if (sw != null) {
                try {
                    sw.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
            if (pw != null) {
                pw.close();
            }
        }
        return result;
    }


    /**
     * 判断异常是否由某些底层的异常引起.
     *
     * @param ex                    xx
     * @param causeExceptionClasses xx
     * @return xx
     */
    public static boolean isCausedBy(Exception ex, Class<? extends Exception>... causeExceptionClasses) {
        Throwable cause = ex;
        while (cause != null) {
            for (Class<? extends Exception> causeClass : causeExceptionClasses) {
                if (causeClass.isInstance(cause)) {
                    return true;
                }
            }
            cause = cause.getCause();
        }
        return false;
    }
}
